﻿//-----------------------------------------------------------------------
// <copyright file="ScheduleRepository.cs" company="FastNET Services">
//     Copyright (c) 2008-2009. All Rights Reserved.
// </copyright>
// <license>
//     GPLv2
// </license>
// <warranty>
//     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
//     BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//     NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
//     DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//     OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </warranty>
//-----------------------------------------------------------------------
#region Usings
using System;
using System.Collections.Generic;
using System.Data.EntityClient;
using System.Linq;
using FastNET.CleanAct.Client.ManagerEngineData.Entities;
using FastNET.CleanAct.Common.Repository;
using FastNET.CleanAct.Common.Repository.Interfaces.DataInterfaces.ManagementEngine;
using FastNET.CleanAct.Common.Repository.Interfaces.Repositories.ManagementEngine;

#endregion

namespace FastNET.CleanAct.Client.ManagerEngineData.Repositories
{
    /// <summary>
    /// General repository for managing Schedules
    /// </summary>
    internal class ScheduleRepository
        : IScheduleRepository
    {
        #region CTor/DTor

        /// <summary>
        /// Initializes a new instance of the ScheduleRepository class
        /// </summary>
        /// <param name="connection">Reference to the common EntityConnection for the repository</param>
        internal ScheduleRepository(EntityConnection connection)
        {
            Connection = connection;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets a reference to the common EntityConnection for the repository
        /// </summary>
        protected EntityConnection Connection { get; private set; }

        #endregion

        #region IRepository<IScheduleData> Members

        /// <summary>
        /// Retrieves all instances of ILogEntryData from the repository
        /// </summary>
        /// <returns>IEnumerable of the requested IData</returns>
        public IList<IScheduleData> Retrieve()
        {
            List<IScheduleData> returnValues = new List<IScheduleData>();

            using (ManagerDataEntities dataSource = new ManagerDataEntities(Connection))
            {
                IEnumerable<Schedule> query = from item in dataSource.Schedules select item;

                foreach (Schedule item in query)
                {
                    returnValues.Add(item);
                    dataSource.Detach(item);
                }
            }

            return returnValues;
        }

        /// <summary>
        /// Retrieves the requested IScheduleData by an Identity
        /// </summary>
        /// <param name="ID">Identity to retrieve the data by</param>
        /// <returns>IScheduleData instance or null if one was not found</returns>
        /// <exception cref="InvalidCastException">Thrown if the identity is of the wrong type for this datasource</exception>
        public IScheduleData Retrieve(Identity ID)
        {
            if (!ID.CanFitInGuid())
            {
                throw new InvalidCastException(string.Format("Identity for this type of repository requires it to be of Guid Type. Currently is {0}.", ID.UnderlyingType()));
            }

            // This has to be done here because LINQ does not support the inline case
            Guid searchID = ID;

            using (ManagerDataEntities dataSource = new ManagerDataEntities(Connection))
            {
                Schedule foundItem = (from
                                                item
                                                in
                                          dataSource.Schedules
                                      where
                                          item.ScheduleID == searchID
                                      select
                                          item).FirstOrDefault();

                if (foundItem != null)
                {
                    dataSource.Detach(foundItem);
                }

                return foundItem;
            }
        }

        /// <summary>
        /// Deletes the requested IScheduleData
        /// </summary>
        /// <param name="Data">IScheduleData to delete from the repository</param>
        /// <exception cref="ArgumentNullException">Thrown if data is null</exception>
        /// <exception cref="InvalidCastException">Thrown if the data is of the wrong type for this datasource</exception>
        /// <exception cref="InvalidOperationException">Thrown if the IScheduleData is new or already deleted</exception>
        public void Delete(IScheduleData Data)
        {
            if (Data == null)
            {
                throw new ArgumentNullException("Data", "Must have a valid Data to delete");
            }

            if (!(Data is Schedule))
            {
                throw new InvalidCastException("Data is not of type Schedule. Cannot delete this object through this repository");
            }

            if (Data.IsNew)
            {
                throw new InvalidOperationException("Data cannot be new before deleting. There is nothing to delete.");
            }

            if (Data.IsDeleted)
            {
                throw new InvalidOperationException("Data already deleted.");
            }

            using (ManagerDataEntities dataSource = new ManagerDataEntities(Connection))
            {
                dataSource.Attach((Schedule)Data);
                dataSource.DeleteObject(Data);
                dataSource.SaveChanges();
            }
        }

        /// <summary>
        /// Saves the requested IScheduleData
        /// </summary>
        /// <param name="Data">IScheduleData to save to the repository</param>
        /// <exception cref="ArgumentNullException">Thrown if data is null</exception>
        /// <exception cref="InvalidCastException">Thrown if the data is of the wrong type for this datasource</exception>
        public void Save(IScheduleData Data)
        {
            if (Data == null)
            {
                throw new ArgumentNullException("Data", "Must have a valid Data to delete");
            }

            if (!(Data is Schedule))
            {
                throw new InvalidCastException("Data is not of type Schedule. Cannot save this object through this repository");
            }

            if (!Data.IsDirty)
            {
                return;
            }

            using (ManagerDataEntities dataSource = new ManagerDataEntities(Connection))
            {
                if (Data.IsNew)
                {
                    dataSource.AddToSchedules((Schedule)Data);
                    dataSource.SaveChanges();
                    dataSource.Detach(Data);
                }
                else
                {
                    dataSource.ApplyPropertyChanges("Schedules", Data);
                    dataSource.SaveChanges();
                }
            }
        }

        /// <summary>
        /// Creates a new instance of IScheduleData
        /// </summary>
        /// <returns>New Instance of IScheduleData</returns>
        public IScheduleData Create()
        {
            return new Schedule();
        }

        #endregion
    }
}